﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace SharpMedia
{
    public class InterfaceLock
    {
        public object lockObject = new object();
        
        int locks = 0;
        bool locked = false;

        public event EventHandler Unlocked;

        public bool WaitingForLock
        {
            get
            {
                return locks > 0 && !locked;
            }
        }


        public bool IsLocked
        {
            get
            {
                lock (lockObject)
                    return locked;
            }
        }
        
        public void WaitForLock()
        {
            Monitor.Enter(lockObject);
            locks++;
            while (!locked)
                Monitor.Wait(lockObject);
            Monitor.Exit(lockObject);
        }

        public void WorkDone()
        {
            lock (lockObject)
            {
                locks--;
                if (locks == 0)
                {
                    locked = false;
                    if (Unlocked != null)
                        Unlocked(this, null);
                }
                Monitor.PulseAll(lockObject);
            }
        }

        public void Lock()
        {
            Monitor.Enter(lockObject);
            locked = true;
            Monitor.PulseAll(lockObject);
            Monitor.Exit(lockObject);
        }

    }
}
